import { defineStore } from 'pinia'
import { IHandleApi } from 'vue3-common/types'
import { IPeriodDay, IPeriodSetting } from '@/types/period.ts'
import {
  getMenstruateFirstDateApi,
  queryPeriodDayApi,
  queryPeriodSettingApi,
  updatePeriodDayApi,
  updatePeriodSettingApi
} from '@/apis/period.ts'
import { getCurrentMonth } from 'vue3-common/utils/dateUtil'

export const usePeriodStore = defineStore('period', {
  state: () => ({
    periodDayList: [] as IPeriodDay[],
    periodSetting: {
      id: 0,
      cycleLength: 0,
      duration: 0,
      isCalculate: false
    } as IPeriodSetting,
    menstruateFirstDate: '',
    queryInfo: {
      month: getCurrentMonth()
    },
    selectDate: '',
    currentPeriodDay: {
      crampLevel: '',
      date: '',
      flowLevel: '',
      isMenstruate: false,
      sexActivity: ''
    } as IPeriodDay,
    travelSpotApiType: 'ADD' as IHandleApi,
    isRefresh: false
  }),
  actions: {
    async queryPeriodDayList() {
      this.periodDayList = await queryPeriodDayApi(this.queryInfo.month)
    },
    async updatePeriodDay() {
      await updatePeriodDayApi(this.currentPeriodDay.id as number, this.currentPeriodDay)
      await this.refreshInfo()
    },
    async queryPeriodSetting() {
      this.periodSetting = await queryPeriodSettingApi()
    },
    async updatePeriodSetting() {
      await updatePeriodSettingApi(this.periodSetting.id as number, this.periodSetting)
      await this.refreshInfo()
    },
    async getMenstruateFirstDate(month: string) {
      this.menstruateFirstDate = await getMenstruateFirstDateApi(month)
    },
    async refreshInfo() {
      await this.queryPeriodDayList()
      await this.queryPeriodSetting()
      this.isRefresh = !this.isRefresh
    },
    getPeriodDay(date: string): IPeriodDay {
      const result = this.periodDayList.find((item) => item.date === date)
      if (result) {
        return result
      } else {
        return this.getEmptyPeriodDay(date)
      }
    },
    getEmptyPeriodDay(date: string): IPeriodDay {
      return {
        id: 0,
        crampLevel: '',
        date,
        flowLevel: '',
        isDrug: false,
        isMenstruate: false,
        sexActivity: ''
      }
    }
  }
})
